package com.lei.hash;

import java.util.HashSet;
import java.util.Set;

/**
 * LeetCode 202. 快乐数
 */
public class IsHappy {
    public boolean is(int n){
        Set<Integer> set = new HashSet<Integer>();
        //当出现过的数再次出现的时候退出循环
        while(n != 1 && !set.contains(n)){
            set.add(n);
            n = getNextNum(n);
        }
        return n == 1;
    }

    private int getNextNum(int n) {
        int res = 0;
        while(n > 0){
            //一个数的每个位置的数如何相加
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }

    public static void main(String[] args) {
        int a = 19;
        int b = 2;
        IsHappy i = new IsHappy();
        System.out.println(i.is(a));
        System.out.println(i.is(b));
    }
}
